import selenium
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
import colorful
import platform
from zq_tools.zq_logger import default_logger as logger


is_windows = platform.system()=="Windows"
logger.info(f"is_windows={is_windows}")


import zq_logger
logger = zq_logger.get_logger(
    logger_name = "reporter",
    log_path = "./log.txt",
    enable_file = True,
    enable_console=True
)

if is_windows:
    import sys
    sys.path.append("./update-chromedriver")
    from download_matched_chromedriver import check_and_update
    check_and_update(".\\chromedriver.exe")

import os
current_dir, _ = os.path.split(__file__)
print(f"file={__file__}")
print(f"current_dir={current_dir}")
chromedriver_path = "chromedriver.exe" if is_windows else "chromedriver"
chromedriver_path = os.path.join(current_dir, chromedriver_path)
chromedriver_path = os.path.abspath(chromedriver_path)
print(f"chromedriver_path={chromedriver_path}")



class Health_reporter:
    def __init__(self):
        logger.info("Init Health_reporter")
        if not is_windows:
            from pyvirtualdisplay import Display
            self.display = Display(visible=0)
            self.display.start()
        self.config = self.get_config_from_json()
        self.config['main_url'] = 'https://weixine.ustc.edu.cn/2020'
        self.config['login_url'] = 'https://weixine.ustc.edu.cn/2020/login'
        self.config['home_url'] = 'https://weixine.ustc.edu.cn/2020/home'
        logger.info(f"Config: {self.config}")

    def mainloop(self):
        while True:
            import time
            self.login()
            self.report()
            time.sleep(self.config['interval_hours']*3600)
        

    def login(self):
        opt = Options()
        if not is_windows:
            opt.add_argument('--no-sandbox')
            opt.add_argument('--disable-dev-shm-usage')
            opt.add_argument('--headless')
            opt.add_argument('--disable-gpu')
        self.browser = webdriver.Chrome(executable_path=chromedriver_path, chrome_options=opt)
        b = self.browser
        b.get(self.config['main_url'])
        if b.current_url == self.config['login_url']:
            login_link = b.find_element_by_link_text("统一身份认证登录")
            login_link.click()
            input_username = b.find_element_by_xpath("//input[@id='username']")
            input_password = b.find_element_by_xpath("//input[@id='password']")
            input_username.send_keys(self.config['uid'])
            input_password.send_keys(self.config['password'])
            button_login = b.find_element_by_xpath("//button[@id='login']")
            button_login.click()
        assert(b.current_url == self.config['home_url'])
    
    def report(self):
        import time
        time.sleep(5) # wait for data loading
        b = self.browser
        button_report = b.find_element_by_xpath('//*[@id="report-submit-btn-a24"]')
        button_report.click()
        time.sleep(5) # wait for report submitting
        current_time = time.time()
        next_report_time = current_time + self.config['interval_hours']*3600
        current_time = time.localtime(current_time)
        next_report_time = time.localtime(next_report_time)
        current_time = time.strftime("%Y/%m/%d %H:%M:%S", current_time)
        next_report_time = time.strftime("%Y/%m/%d %H:%M:%S", next_report_time)
        logger.info(f"成功上报健康信息！上报时间：{current_time}\t预计下次上报时间：{next_report_time}")
        b.close()
        
    def get_config_from_json(self)->dict:
        import json
        with open("config.json","r") as f:
            json_str = f.read()
        config = json.loads(json_str)
        return config

if __name__ == '__main__':
    h = Health_reporter()
    try:
        health_reporter = Health_reporter()
        health_reporter.mainloop()
    except:
        logger.error("Encounter some problems", exc_info=True)
    
